package org.yanghe.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
public class PHystarixFallBackController {

    @Value("${server.port}")
    private String port;

    @GetMapping(value = "/provider/hystrix/ok/{name}")
    public String providerOK(@PathVariable("name") String name){
        return name+" Print From Provider[OK] "+port;
    }

    @GetMapping(value = "/provider/hystrix/timeout/{name}")
    @HystrixCommand(fallbackMethod = "providerTimeOutHandler",commandProperties = {
            //规定三秒以内的逻辑为正常逻辑
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "3000")
    })
    public String providerTimeOut(@PathVariable("name") String name){
        //int a=10/0; 错误也可导致调用 providerTimeOutHandler 方法
        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return name+" Print From Provider[TimeOut] "+port;
    }

    /**
     * fallback 方法  当方法出现异常时调用该方法
     * @param name
     * @return
     */
    public String providerTimeOutHandler(@PathVariable("name") String name){
        return name+" Print From providerTimeOutHandler  系统繁忙，请稍后再试！"+port;
    }

}
